import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STPage, STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { BaseAbilityComponent } from 'src/app/shared/base.ability.component';
import {
  DELETED_STATUS_BADGE,
  DELETED_STATUS_ENUM,
  ROLE_PAGE_PARAMS_CACHE_KEY,
  ROLE_TYPE_ENUM,
  ROLE_TYPE_TAG
} from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';
import { AbilityService } from 'src/app/shared/service/ability.service';
import { cacheGet, cacheSet } from 'src/app/shared/utils/cache';

import { RoleEditComponent } from './role-edit.component';
import { RoleMenuComponent } from './role-menu.component';
import { SystemRoleUserComponent } from './role-user.component';
import {HttpContext} from "@angular/common/http";
import {ALLOW_ANONYMOUS} from "@delon/auth";

@Component({
  selector: 'app-system-role',
  templateUrl: './role.component.html'
})
export class SystemRoleComponent extends BaseAbilityComponent implements OnInit, OnDestroy {
  params: any = {};
  filterParmas: any = {};
  page: any = {
    data: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {
    properties: {
      name: {
        type: 'string',
        title: '角色名称',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      type: {
        type: 'string',
        title: '类型',
        enum: ROLE_TYPE_ENUM,
        default: 0,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      },
      deleted: {
        type: 'string',
        title: '状态',
        default: false,
        enum: DELETED_STATUS_ENUM,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      }
    }
  };
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: 'ID', index: 'id' },
    { title: '角色名称', index: 'name' },
    { title: '角色类型', index: 'id', type: 'tag', tag: ROLE_TYPE_TAG },
    { title: '状态', index: 'enable', type: 'badge', badge: DELETED_STATUS_BADGE },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          icon: 'edit',
          type: 'modal',
          modal: {
            component: RoleEditComponent
          },
          click: () => {
            this.query();
          },
          acl: { ability: ['edit'] }
        },
        {
          text: '用户',
          icon: 'user',
          type: 'modal',
          modal: {
            component: SystemRoleUserComponent
          }
        },
        {
          text: '删除',
          icon: 'delete',
          iif: record => !record.deleted && record.type !== 5,
          click: (record: any) => {
            this.delete(record);
          },
          acl: { ability: ['delete'] }
        }
      ]
    }
  ];

  constructor(
    protected http: _HttpClient,
    private modal: ModalHelper,
    private modalService: NzModalService,
    private msg: NzMessageService,
    private router: Router,
    protected override route: ActivatedRoute,
    protected override ability: AbilityService
  ) {
    super(route, ability);
  }

  ngOnInit() {
    super.initAbilities();
    const initParams = cacheGet(ROLE_PAGE_PARAMS_CACHE_KEY);
    this.filterParmas = initParams || {};
    if (this.filterParmas) {
      if (this.filterParmas.pageNum) {
        this.page.current = this.filterParmas.pageNum;
        delete this.filterParmas.pageNum;
      }
      if (this.filterParmas.pageSize) {
        this.page.size = this.filterParmas.pageSize;
        delete this.filterParmas.pageSize;
      }
    }
    this.query();
  }

  ngOnDestroy(): void {
    super.clearAbilities();
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query();
    }
  }

  filterQuery(event: any) {
    this.filterParmas = event;
    if (this.filterParmas.type == 0) {
      delete this.filterParmas.type;
    }
    this.query();
  }

  resetQuery() {
    this.filterParmas = {};
    this.query();
  }

  query() {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    this.http.get(Api.BaseRoleApi, this.filterParmas,{context: new HttpContext().set(ALLOW_ANONYMOUS, true)}).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res;
      }
    });
  }

  toSetMenu(record: any) {
    cacheSet(ROLE_PAGE_PARAMS_CACHE_KEY, { pageNum: this.page.current, pageSize: this.page.size, ...this.filterParmas }, 30 * 60 * 1000);
    const data = { id: record.id, name: record.name, code: record.code, deleted: record.deleted, description: record.description };
    this.router.navigate(['/system/role-menu'], {
      queryParams: data
    });
  }

  toSetResource(record: any) {
    cacheSet(ROLE_PAGE_PARAMS_CACHE_KEY, { pageNum: this.page.current, pageSize: this.page.size, ...this.filterParmas }, 30 * 60 * 1000);
    const data = { id: record.id, name: record.name, code: record.code, deleted: record.deleted, description: record.description };
    this.router.navigate(['/system/role-resource'], {
      queryParams: data
    });
  }

  add() {
    this.modal.createStatic(RoleEditComponent).subscribe(() => this.st.reload());
  }

  delete(record: any) {
    console.log(record);
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">如果您确定要删除请点击确定按钮，否则点取消</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http.delete(Api.BaseRoleApi + record.id).subscribe((res: any) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.st.reload();
              this.msg.success('删除成功');
            } else {
              this.msg.warning(res.message);
            }
          } else {
            this.msg.error('删除失败，未知错误');
          }
        }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
}
